package com.eportal.action.background;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.PayOrder;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TLock;
import com.eportal.domain.ThridpayBill;
import com.eportal.domain.TpayWalletlst;
import com.eportal.domain.TuserWallet;
import com.eportal.service.PayOrderService;
import com.eportal.service.PayWalletlstService;
import com.eportal.service.RedEnvService;
import com.eportal.service.ThridpayBillService;
import com.eportal.service.UserWalletService;
import com.eportal.util.Config;
import com.eportal.util.DateUtils;
import com.eportal.util.HomePageConfig;
import com.eportal.util.HttpHelper;
import com.eportal.util.HttpUtil;
import com.eportal.util.MD5;
import com.eportal.util.MdExpiringMap;
import com.eportal.util.SmsHelper;
import com.eportal.util.VerifyCodeHelper;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONObject;

/**
 * 我的钱包
 * @author wangk
 *
 */
public class UserWalletAction extends BaseAction implements ModelDriven<TuserWallet> {
	
 
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(UserWalletAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    private UserWalletService  tUserWalletService;
    
    @Autowired
    private ThridpayBillService thridpayBillService;
    
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private RedEnvService redEnvService;
    
    @Autowired
    private PayWalletlstService payWalletlstService;
    
    
    
    /**
     * 处理菜单
     */
    void doMenu(){
    	String homePageConfig = HomePageConfig.USER_WALLET;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	String act = getRequest().getParameter("act");
    	if(act==null){
    		act="1";
    	}
    	getRequest().setAttribute("act", act);
    }
    private static MdExpiringMap<String, String> randomMap = new MdExpiringMap(3600,500);
    
	/**
     * 我的钱包
     */
    public String listView() {
    	try{
    		doMenu();
    		String vtype = getRequest().getParameter("vtype");//展示的类型，比如充值，充值记录等
    		if(vtype!=null){
    			String random = getRequest().getParameter("random");
    			if(randomMap.get(random)==null){
    				getRequest().setAttribute("vtype", vtype);	
    			}else{
    				randomMap.put(random, "");
    			}
    		}
    		
        	Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	int userRole =  (Integer) getSession().getAttribute("userRole");
        	getRequest().setAttribute("userRole", userRole);
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}
        	BigDecimal amount = wallet.getAmount();//可用余额
        	BigDecimal amountRollOut = new BigDecimal(0);
        	BigDecimal amountSum = new BigDecimal(amount.toString()).add(amountRollOut);//总余额=可用+提现中的
        	getRequest().setAttribute("amount", amount);
        	getRequest().setAttribute("amountRollOut", amountRollOut);
        	getRequest().setAttribute("amountSum", amountSum);
        	String sql = "select count(1) renums from t_redenvmain t1,t_redenvdetail t2 where t1.sid = t2.remainid and t1.optid= '"+user.getSid()+"'"+" and t2.envstatus in ('1','2')";
        	List<Map<String, String>> list = redEnvService.listBySql(sql);
        	String redenv = String.valueOf(list.get(0).get("renums"));
        	getRequest().setAttribute("redenv", redenv);
    	}catch(Exception e){
    		log.error(this, e);
    		getRequest().setAttribute("msg", "不支持访问该页面");
    		return "exception";
    	}
        return SUCCESS;
    }
    
    /**
     * 
     * @return
     */
    public void list() {
		List datalist = new ArrayList();
    	try{
    		String type=getRequest().getParameter("type");//
			JqGridPager page = new JqGridPager();

			String orderid = getRequest().getParameter("orderid");
			String datefrom = getRequest().getParameter("datefrom");
			String dateto = getRequest().getParameter("dateto");
			
    		if("2".equals(type)){
    			Sysopt  user = (Sysopt)getSession().getAttribute("user");
    			TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    			String where = " GENERALSUBJECT='10002'  and S_WID='"+wallet.getWid()+"'";
    			if(StringUtils.isNotBlank(orderid)){
    				where += " and a.pay_no like '%"+orderid+"%'";
    			}
    			if(StringUtils.isNotBlank(datefrom)){
    				where += " and a.CREDITTIME >= to_date( '"+datefrom+"' ,'yyyy-mm-dd')";
    			}
    			if(StringUtils.isNotBlank(dateto)){
    				where += " and a.CREDITTIME <= to_date( '"+dateto+"' ,'yyyy-mm-dd')";
    			}
    				
    			page.setWhere(where);
    	        setPage(getRequest(), page);
    	        //List<TpayWalletlst> list = tUserWalletService.list(page);
    	        List<Map<String,Object>> list = tUserWalletService.listBySql(page);
    			Map map;
    			if(list!=null){
    				for(Map bean:list){
        				map = new HashMap();
        				map.put("AMOUNT", bean.get("DEBITSIDECASH").toString().replace("-", ""));//去掉负号
        				map.put("STATUS", bean.get("STATUS"));
        				map.put("OPTID", "");
        				map.put("SID", bean.get("SID"));
        				map.put("PAYEE_ACCOUNT", "其他");
        				map.put("APPLY_DATE", "");
        				map.put("TO_DATE", "");
        				map.put("CNAME", bean.get("CNAME"));
        				map.put("PAY_NO",bean.get("PAY_NO"));
        				Date d = (Date)bean.get("CREDITTIME");
    					//String appllyDate =  String.valueOf(bean.get("CREDITTIME");//DateUtils.stringToDate(String.valueOf(bean.get("CREDITTIME")), DateUtils.DateStyle.YYYY_MM_DD_HH_MM_SS);
    					map.put("APPLY_DATE", DateUtils.formatDatetime(d));
    					if("0".equals(bean.get("STATUS"))){
    						map.put("STATUS_", "受理中");	
    					}
    					if("2".equals(bean.get("STATUS"))){
    						map.put("STATUS_", "提现失败");	
    					}
    					if("1".equals(bean.get("STATUS"))){
    						map.put("STATUS_", "已到账");	
    					}
    					map.put("STATUS",bean.get("STATUS"));
        				ThridpayBill bill = thridpayBillService.get(Long.valueOf(String.valueOf(bean.get("THRID_BILL_ID"))));
        				if(bill!=null){
        					if(bill.getResulttime()!=null&&"1".equals(bean.get("STATUS"))){
        						String toDate =  DateUtils.formatDatetime(new Date(bill.getResulttime().getTime()));
        						map.put("TO_DATE", toDate);
        					}
        					if("10001".equals(bill.getDepartid())){
        						map.put("PAYEE_ACCOUNT", "支付宝");
        					}else if("10002".equals(bill.getDepartid())){
        						map.put("PAYEE_ACCOUNT", "微信");
        					}
        				}
        				datalist.add(map);
        			}
    			}
    			
    		}
    		if("3".equals(type)){
    			Sysopt  user = (Sysopt)getSession().getAttribute("user");
    			TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    			String where = " GENERALSUBJECT='10001'  and S_WID='"+wallet.getWid()+"' and c.mtype='qr'";
    			if(StringUtils.isNotBlank(orderid)){
    				where += " and a.pay_no like '%"+orderid+"%'";
    			}
    			if(StringUtils.isNotBlank(datefrom)){
    				where += " and a.CREDITTIME >= to_date( '"+datefrom+"' ,'yyyy-mm-dd')";
    			}
    			if(StringUtils.isNotBlank(dateto)){
    				where += " and a.CREDITTIME <= to_date( '"+dateto+"' ,'yyyy-mm-dd')";
    			}
    				
    			page.setWhere(where);
    	        setPage(getRequest(), page);
    	        //List<TpayWalletlst> list = tUserWalletService.list(page);
    	        List<Map<String,Object>> list = tUserWalletService.list4Qrcode(page);
    			Map map;
    			if(list!=null){
    				for(Map bean:list){
        				map = new HashMap();
        				map.put("AMOUNT", bean.get("DEBITSIDECASH").toString().replace("-", ""));//去掉负号
        				map.put("STATUS", bean.get("STATUS"));
        				map.put("OPTID", "");
        				map.put("SID", bean.get("SID"));
        				map.put("PAYEE_ACCOUNT", "其他");
        				map.put("APPLY_DATE", "");
        				map.put("TO_DATE", "");
        				map.put("CNAME", bean.get("CNAME"));
        				map.put("PAY_NO",bean.get("PAY_NO"));
        				Date d = (Date)bean.get("CREDITTIME");
    					//String appllyDate =  String.valueOf(bean.get("CREDITTIME");//DateUtils.stringToDate(String.valueOf(bean.get("CREDITTIME")), DateUtils.DateStyle.YYYY_MM_DD_HH_MM_SS);
    					map.put("APPLY_DATE", DateUtils.formatDatetime(d));

    					if("1".equals(bean.get("STATUS"))){
    						map.put("STATUS_", "已到账");	
    					}
    					map.put("STATUS",bean.get("STATUS"));
        				ThridpayBill bill = thridpayBillService.get(Long.valueOf(String.valueOf(bean.get("THRID_BILL_ID"))));
        				if(bill!=null){
        					if(bill.getResulttime()!=null&&"1".equals(bean.get("STATUS"))){
        						String toDate =  DateUtils.formatDatetime(new Date(bill.getResulttime().getTime()));
        						map.put("TO_DATE", toDate);
        					}
        					if("10001".equals(bill.getDepartid())){
        						map.put("PAYEE_ACCOUNT", "支付宝");
        					}else if("10002".equals(bill.getDepartid())){
        						map.put("PAYEE_ACCOUNT", "微信");
        					}
        				}
        				datalist.add(map);
        			}
    			}
    			
    		}
    		jqGridQueryMap(Map.class, getRequest(), datalist, getResponse(), page);	
    	}catch(Exception e){
    		log.error(this, e);
    	}
  }
    
    public String payOrderView() {
    	try{
    		String orderId = getRequest().getParameter("orderId");
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}
        	BigDecimal amount = wallet.getAmount();//可用余额
        	PayOrder order = payOrderService.get(Long.valueOf(orderId));
        	BigDecimal orderAmount = order.getAmount();
        	getRequest().setAttribute("amount", amount);
        	getRequest().setAttribute("orderId", order.getSid());
        	getRequest().setAttribute("orderAmount", orderAmount);
        	getRequest().setAttribute("cname", order.getCname());
        	if(wallet.getPayPassword()==null){
        		getRequest().setAttribute("payPasswordState","1");	
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		getRequest().setAttribute("msg", "不支持访问该页面");
    		return "exception";
    	}
        return SUCCESS;
    }
    
    
    public String showRollOutResult(){
    	try{
    		String sid = getRequest().getParameter("sid");
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TpayWalletlst walletlst = payWalletlstService.get(Long.valueOf(sid));
    		
    		ThridpayBill bill = thridpayBillService.get(Long.valueOf(walletlst.getThridBillId()));
			List list = new ArrayList();
			if(bill!=null){
				Map map = new HashMap();
				map.put("name", "提现申请");
				map.put("date", DateUtils.formatDatetime(bill.getCreatetime(), "yyyy-MM-dd"));
				map.put("time", DateUtils.formatDatetime(bill.getCreatetime(), "HH:mm:ss"));
				list.add(map);
				
				Map m2 = new HashMap();
				m2.put("name", "提现受理");
				m2.put("date", DateUtils.formatDatetime(bill.getCreatetime(), "yyyy-MM-dd"));
				m2.put("time", DateUtils.formatDatetime(bill.getCreatetime(), "HH:mm:ss"));
				list.add(m2);
				
				Map m3 = new HashMap();
				if("1".equals(walletlst.getStatus())){
					m3.put("name", "转账成功");
					m3.put("date", DateUtils.formatDatetime(bill.getResulttime(), "yyyy-MM-dd"));
					m3.put("time", DateUtils.formatDatetime(bill.getResulttime(), "HH:mm:ss"));
				}else if("2".equals(walletlst.getStatus())){
					m3.put("name", "转账失败");
					m3.put("status", "2");
					m3.put("date", DateUtils.formatDatetime(bill.getResulttime(), "yyyy-MM-dd"));
					m3.put("time", DateUtils.formatDatetime(bill.getResulttime(), "HH:mm:ss"));
				}
				list.add(m3);
			}
			getRequest().setAttribute("datalist",list);
    		getRequest().setAttribute("payNo", walletlst.getPayNo());
    	}catch(Exception e){
    		log.error(this, e);
    		getRequest().setAttribute("msg", "不支持访问该页面");
    		return "exception";
    	}
        return SUCCESS;
    }
    
    public String payOrderByWeixin() {
    	try{
    		String orderId = getRequest().getParameter("orderId");
        	String url = getRequest().getParameter("url");//微信支付二维码
        	PayOrder order = payOrderService.get(Long.valueOf(orderId));
        	getRequest().setAttribute("cname", order.getCname());
        	getRequest().setAttribute("amount", order.getAmount());
        	getRequest().setAttribute("url", url);
        	getRequest().setAttribute("orderId", orderId);
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	return SUCCESS;
    }
    public void payOrder() {
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		String orderId = getRequest().getParameter("orderId");
    		String departid = getRequest().getParameter("departid");
    		String payPassword = getRequest().getParameter("payPassword");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		result.put("code", 0);
        		result.put("msg", "支付失败");
        		responseBody(result);
        		return;
        	}
        	PayOrder order = payOrderService.get(Long.valueOf(orderId));
        	order.setWid(wallet.getWid().toString());
        	payOrderService.update(order);
        	if("0".equals(order.getPstate())){
        		result.put("code", 0);
        		result.put("msg", "订单已完成支付，请勿重复支付");
        		responseBody(result);
        		return;
        	}
        	if(!"1".equals(order.getPstate())){
        		result.put("code", 0);
        		result.put("msg", "订单状态不正确");
        		responseBody(result);
        		return;
        	}
			Map map = new HashMap();
			map.put("apiId", "Api_Wallet_Pay_Request");
			map.put("wid", wallet.getWid());
			map.put("departid", departid);
			map.put("amount", order.getAmount());
			map.put("subject",order.getCname());
			map.put("returnUrl", order.getReturnUrl());
			map.put("payPassword", payPassword);
			map.put("orderId", orderId);
			map.put("clientIp", WebUtil.getIpAddr(getRequest()));
			Map m = new HashMap();
			m.put("requestjson", JSONObject.fromObject(map).toString());
			String str = HttpHelper.doPostForm(m,Config.PAY_SERVICE_URL+"/service/ldo");
			if("0".equals(getResultCode4PayService(str))){
				Map obj = (Map)getObj4PayService(str);
				if("0".equals(obj.get("code"))){
					String url =  (String)obj.get("url");
					result.put("url", url);
					result.put("returnUrl",order.getReturnUrl());
					result.put("code", 1);
					responseBody(result);
			    	return;
				}else{
					result.put("code", 0);
    	    		result.put("msg", "支付失败");
				}
			}else if("10000".equals(getResultCode4PayService(str))){
				if("ERROR_PASSWORD_ERROR_NUM_LIMIT".equals(getResultMessage4PayService(str))){
					result.put("code","pay_error_1");
		    		result.put("msg", "您已连续输错3次密码，请立即修改密码");
				}else{
					result.put("code", 0);
		    		result.put("msg", getResultMessage4PayService(str));	
				}
				
			}else{
				result.put("code", 0);
	    		result.put("msg", "支付失败");
			}
		
        	
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    	return;
    }
    
    /**
     * 充值首页
     * @return
     */
    public String rollInView() {
    	Sysopt  user = (Sysopt)getSession().getAttribute("user");
    	try{
    		String amountName = tUserWalletService.getAmountName(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		if(amountName==null){
    			log.error("amountName is null");
    			return "exception";
    		}
    		
    		
    		getRequest().setAttribute("amountName", amountName);
    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
        return SUCCESS;
    }
    /**
     * 生成充值订单   		
     */
    public void rollInGenBill(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet!=null){
        		String payWay = getRequest().getParameter("payWay");
        		String amount = getRequest().getParameter("amount");
        		if("10001".equals(payWay)){
        			Map map = new HashMap();
        			map.put("apiId", "Api_T_THRIDPAY_BILL_WEB_Request");
        			map.put("wid", wallet.getWid());
        			map.put("departid", "10001");
        			map.put("amount", amount);
        			map.put("subject", "零钱充值");
        			map.put("returnUrl", WebUtil.getReqPreUrl(getRequest())+"admin/userWallet_showPayResult.action?type=rollIn&payid=${payid}");
        			Map m = new HashMap();
        			m.put("requestjson", JSONObject.fromObject(map).toString());
        			String str = HttpHelper.doPostForm(m,Config.PAY_SERVICE_URL+"/service/ldo");
        			if("0".equals(getResultCode4PayService(str))){
        				Map obj = (Map)getObj4PayService(str);
        				if("0".equals(obj.get("code"))){
        					String url =  (String)obj.get("url");
        					if(url!=null){
        						result.put("url", url);
        						result.put("code", 1);
        					}else{
        						result.put("code", 0);
                	    		result.put("msg", "订单生成失败");	
        					}
        				}else{
        					result.put("code", 0);
            	    		result.put("msg", "订单生成失败");
        				}
        			}else{
        				result.put("code", 0);
        	    		result.put("msg", "订单生成失败");
        			}
        		}else{
        			result.put("code", 0);
            		result.put("msg", "未知的支付方式");
        		}
        	}else{
        		result.put("code", 0);
        		result.put("msg", "账户不支持充值");
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    	return;
    }
    
    public String showPayResult(){
    	String msg ="";
    	try{
    		doMenu();
    		String type = getRequest().getParameter("type");
        	String payid = getRequest().getParameter("payid");
        	ThridpayBill bill = thridpayBillService.getByPayId(payid);
        	Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}
        	
        	if(bill!=null){
        		if(bill.getWid().equals(wallet.getWid().toString())){
        			if(ThridpayBill.PSATE_SUCCESS.equals(bill.getPstate())){
            			msg="恭喜，您已成功充值"+bill.getAmount()+"元。";
            		}else{
            			msg="订单可能在结算中，请稍后再试。";
            		}
        		}else{
        			msg="订单不存在或者没有权限访问";
        		}
        	}else{
        		msg="找不到对应的订单";
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		msg="订单异常";
    	}
    	getRequest().setAttribute("msg", msg);
    	return SUCCESS;
    }
    

    
    static String getResultCode4PayService(String result){
    	return JSONObject.fromObject(result).getJSONObject("status").getString("resultcode");
    }
    
    static String getResultMessage4PayService(String result){
    	return JSONObject.fromObject(result).getJSONObject("status").getString("resultmssage");
    }
    
    static Object getObj4PayService(String result){
    	return JSONObject.toBean(JSONObject.fromObject(result).getJSONObject("pageList"), Map.class);
    }
    
    
    /**
     * 提现首页
     * @return
     */
    public String rollOutView() {
    	Sysopt  user = (Sysopt)getSession().getAttribute("user");
    	try{
    		TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		if(walletTel==null){
    			getRequest().setAttribute("msg", "未绑定手机或未开通钱包");
    			return "exception";	
    		}else{
    			getRequest().setAttribute("walletTel", walletTel);
    			getRequest().setAttribute("walletTel_", walletTel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));//中间4位打星号
    		}
        	if(wallet.getPayPassword()==null){
        		getRequest().setAttribute("payPasswordState","1");	
        	}
    	}catch(Exception e){
    		log.error(this, e);
			return "exception";	
    	}
    	
        return SUCCESS;
    }
    
    /**
     * 提现-选择提现方式
     * @return
     */
    public String rollOutChoiceWay() {
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		//TODO 开发阶段先不使用
    		//SmsHelper.remove("rollout", walletTel);//清空取现的短信验证码，防止验证码被重复使用
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet!=null){
        		BigDecimal amount = wallet.getAmount();
        		if(amount==null){
        			amount = new BigDecimal(0);
        		}
        		getRequest().setAttribute("amount", amount);
        	}else{
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
        return SUCCESS;
    }
    
    
    /**
     * 提现，发送短信
     */
    public void sendSms4RollOut(){
    	try{
    		String img_code = getRequest().getParameter("img_code");
    		if(VerifyCodeHelper.checkCode(getSession(), VerifyCodeHelper.FUNC_WALLET_ROLLOUT, img_code)){
    			Sysopt  user = (Sysopt)getSession().getAttribute("user");
        		String code = "" + System.currentTimeMillis();
    			code = code.substring(code.length() - 6);
            	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
            	String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
            	if(walletTel==null){
            		result.put("code", 0);
            		result.put("msg", "账户未绑定手机号或未开通钱包功能");
            	}else{
            		SmsHelper.sendSMSVaildCode("rollout",walletTel, "您的提现验证码为"+code, code);
            		result.put("code", 1);
            	}
    		}else{
    			result.put("code", 0);
        		result.put("msg", "图片验证码不正确，请重新确认或刷新验证码");
    		}
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "发送失败");
    	}
    	responseBody(result);
    	return;
    }
    
    public void checkSms4RollOut(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		String sms_code = getRequest().getParameter("sms_code");
    		String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		String img_code = getRequest().getParameter("img_code");
    		if(VerifyCodeHelper.checkCode(getSession(), VerifyCodeHelper.FUNC_WALLET_ROLLOUT, img_code)){
    			if(SmsHelper.checkSMSValidCache("rollout", walletTel, sms_code,20*60*1000l)){
        			result.put("code", 1);
            		result.put("msg", "成功");
        		}else{
        			result.put("code", 0);
            		result.put("msg", "验证码不正确");
        		}
    		}else{
    			result.put("code", 0);
        		result.put("msg", "图片验证码不正确，请重新确认或刷新验证码");
    		}
    		
    		
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    	return;
    }
    
    public void rollOut(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		String amount = getRequest().getParameter("amount");
    		String payPassword = getRequest().getParameter("payPassword");
    		String departid = getRequest().getParameter("departid");
    		String payee_account = getRequest().getParameter("payee_account");
    		String payee_real_name = getRequest().getParameter("payee_real_name");
    		
    		TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		
    		if("10001".equals(departid)){
    			Map map = new HashMap();
    			map.put("apiId", "Api_Wallet_Tranfer_Request");
    			map.put("wid", wallet.getWid());
    			map.put("departid", departid);
    			map.put("amount", amount);
    			map.put("payPassword", payPassword);
    			map.put("payee_account", payee_account);
    			map.put("payee_real_name", payee_real_name);
    			map.put("optid", user.getSid());
    			Map m = new HashMap();
    			m.put("requestjson", JSONObject.fromObject(map).toString());
    			String str = HttpHelper.doPostForm(m,Config.PAY_SERVICE_URL+"/service/ldo");
    			log.info(str);
    			if("0".equals(getResultCode4PayService(str))){
    				Map obj = (Map)getObj4PayService(str);
    				if("0".equals(obj.get("code"))){
    					String url =  (String)obj.get("url");
    					result.put("code", 1);
    					responseBody(result);
    			    	return;
    				}else{
    					result.put("code", 0);
        	    		result.put("msg", obj.get("msg"));
    				}
    			}else if("10000".equals(getResultCode4PayService(str))){
    				result.put("code", 0);
    	    		result.put("msg", getResultMessage4PayService(str));
    			}else{
    				result.put("code", 0);
    	    		result.put("msg", "提现失败");
    			}
    		}else{
    			result.put("code", 0);
        		result.put("msg", "不支持的提现方式");
    		}
    		
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    	return;
    }
    
    public String rollOutSuccess(){
    	return SUCCESS;
    }
    
    
    
    /**
     * 充值-选择充值方式
     * @return
     */
    public String rollInChoiceWay() {
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	getRequest().setAttribute("amount", getRequest().getParameter("amount"));
    		String amountName = tUserWalletService.getAmountName(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
    		if(amountName==null){
    			log.error("amountName is null");
    			return "exception";
    		}
    		getRequest().setAttribute("amountName", amountName);
    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
        return SUCCESS;
    }
    /**
     * 支付密码主页
     * @return
     */
    public String payPasswordView(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}else{
        		if(wallet.getPayPassword()==null){
        			getRequest().setAttribute("state", "1");
        		}else{
        			getRequest().setAttribute("state", "2");
        		}
        		String amountName = tUserWalletService.getAmountName(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        		getRequest().setAttribute("amountName", amountName);
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		getRequest().setAttribute("msg", "不支持访问该页面");
    		return "exception";
    	}
        return SUCCESS;
    }
    
    public String updatePayPasswordView(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}else{
        		String amountName = tUserWalletService.getAmountName(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        		getRequest().setAttribute("amountName", amountName);
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		getRequest().setAttribute("msg", "不支持访问该页面");
    		return "exception";
    	}
        return SUCCESS;
    }
    
    /**
     * 设置、修改支付密码，发送短信
     */
    public void sendSms4PayPassword(){
    	try{
    		String tel = getRequest().getParameter("tel");
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
    		String code = "" + System.currentTimeMillis();
			code = code.substring(code.length() - 6);
    		
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(walletTel==null){
        		result.put("code", 0);
        		result.put("msg", "账户未绑定手机号或未开通钱包功能");
        	}else if(tel!=null&&tel.equals(walletTel)){
        		SmsHelper.sendSMSVaildCode("payPassword",tel, "您的支付密码验证码为"+code, code);
        		result.put("code", 1);
        		result.put("msg", "操作成功");
        	}else{
        		result.put("code", 0);
        		result.put("msg", "与绑定手机号码不符");
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "发送失败");
    	}
    	responseBody(result);
    	return;
    }
    
    public void updatePayPassword(){
    	try{
    		String tel = getRequest().getParameter("tel");
    		String code = getRequest().getParameter("code");
    		String payPassword = getRequest().getParameter("payPassword");
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	String walletTel = tUserWalletService.getTelForWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(payPassword.length()!=6){
        		result.put("code", 0);
        		result.put("msg", "请输入6位支付密码");
        		responseBody(result);
            	return;
        	}
        	code = code.trim();
        	if(walletTel==null){
        		result.put("code", 0);
        		result.put("msg", "账户未绑定手机号或未开通钱包功能");
        	}else if(tel!=null&&tel.equals(walletTel)){
        		if(SmsHelper.checkSMSValidCache("payPassword", tel, code)){
        			tUserWalletService.updatePayPassword(wallet.getWid(),MD5.MD5Encode(payPassword));
        			result.put("code", 1);
            		result.put("msg", "操作成功");
        		}else{
        			result.put("code", 0);
            		result.put("msg", "验证码不正确");
        		}
        	}else{
        		result.put("code", 0);
        		result.put("msg", "与绑定手机号码不符");
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    	return;
    }
    

    
    /**
     * 显示支付页面
     */
    public String showPay(){
    	try{
    		Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	String orderId = getRequest().getParameter("orderId");
        	String callbackUrl = getRequest().getParameter("callbackUrl");
        	String notifyUrl = getRequest().getParameter("notifyUrl");
        	if(orderId==null||callbackUrl==null){
        		getRequest().setAttribute("msg", "参数不正确");
        		return "exception";
        	}
        	if(wallet!=null){
        		getRequest().setAttribute("wallet_amount", wallet.getAmount());
        		PayOrder order = payOrderService.get(Long.valueOf(orderId));
        		getRequest().setAttribute("order_amount", order.getAmount());
        		getRequest().setAttribute("callbackUrl", callbackUrl);
        		getRequest().setAttribute("notifyUrl", notifyUrl);
        		return SUCCESS;
        	}else{
        		getRequest().setAttribute("msg", "用户不支持支付");
        		return "exception";
        	}
    	}catch(Exception e){
    		log.error(this, e);
    		return "exception";
    	}
    }
    
    
    /**
     * 提交支付
     * @return
     */
    public void commitPay(){
    	try{
    		String departid = getRequest().getParameter("departid");
    		String orderId = getRequest().getParameter("orderId");
    		String payPassword = getRequest().getParameter("payPassword");
    		PayOrder order = payOrderService.get(Long.valueOf(orderId));
    		if("10001".equals(departid)||"10002".equals(departid)||"10004".equals(departid)){
    			Map map = new HashMap();
    			map.put("apiId", "Api_T_THRIDPAY_BILL_WEB_Request");
    			map.put("wid", order.getWid());
    			map.put("departid", departid);
    			map.put("amount", order.getAmount());
    			map.put("subject", order.getCname());
    			map.put("payPassword",payPassword);
    			map.put("returnUrl", order.getReturnUrl());
    			map.put("clientIp", WebUtil.getIpAddr(getRequest()));
    			Map m = new HashMap();
    			m.put("requestjson", JSONObject.fromObject(map).toString());
    			String str = HttpHelper.doPostForm(m,Config.PAY_SERVICE_URL+"/service/ldo");
    			if("0".equals(getResultCode4PayService(str))){
    				Map obj = (Map)getObj4PayService(str);
    				if("0".equals(obj.get("code"))){
    					String url =  (String)obj.get("url");
    					if(url!=null){
    						result.put("url", url);
    						result.put("code", 1);
    					}else{
    						result.put("code", 0);
            	    		result.put("msg", "订单生成失败");	
    					}
    				}else{
    					result.put("code", 0);
        	    		result.put("msg", "订单生成失败");
    				}
    			}else{
    				result.put("code", 0);
    	    		result.put("msg", "订单生成失败");
    			}
    		
    		}else{
    			
    		}
    		return;
    	}catch(Exception e){
    		log.error(this, e);
    		return;
    	}
    }
    
    public void checkPayState4Order(){
    	try{
    		String orderId = getRequest().getParameter("orderId");
    		PayOrder order = payOrderService.get(Long.valueOf(orderId));
    		result.put("code", 1);
    		result.put("msg", "");
    		result.put("pstate", order.getPstate());
    		result.put("returnUrl", order.getReturnUrl());
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", 0);
    		result.put("msg", "操作失败");
    	}
    	responseBody(result);
    }
    
    
	@Override
	public TuserWallet getModel() {
		// TODO Auto-generated method stub
		return null;
	}

    
    
    
    
}
